<!--
  * 入库单
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form :model="queryForm" labelAlign="left">
      <a-row :gutter="[8, 10]">
        <a-col :span="{ sm: 7, md: 6 }">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="queryForm.create_time" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="业务员" class="smart-margin-bottom0">
            <Select name="Salesman" v-model:value="queryForm.salesman_id" placeholder="业务员" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="司机" class="smart-margin-bottom0">
            <Select name="Driver" v-model:value="queryForm.driver_id" placeholder="司机" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="入库仓库" name="warehouse_id" class="smart-margin-bottom0">
            <Select name="Warehouse" v-model:value="queryForm.warehouse_id" :fetch-params="selectFetchParams.warehouse" placeholder="请选择仓库" @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch" v-privilege="'goods:query'">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQueryData" v-privilege="'goods:query'">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
            <SearchFormCollapse v-model="expand" />
          </a-button-group>
        </a-col>
        <template v-if="expand">
          <a-col :span="4">
            <a-form-item label="入库类型" class="smart-margin-bottom0">
              <EnumSelect enum-name="INTO_STATUS_ENUM" v-model:value="queryForm.related_type" placeholder="入库类型" @submit="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="入库状态" class="smart-margin-bottom0">
              <EnumSelect enum-name="STORE_STATUS_ENUM" v-model:value="queryForm.into_status" placeholder="入库状态" @submit="onSearch" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item label="单据编号" class="smart-margin-bottom0">
              <a-input v-model:value.trim="queryForm.no" placeholder="单据编号" allow-clear />
            </a-form-item>
          </a-col>
        </template>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button @click="onExport" type="primary" v-privilege="'goods:exportGoods'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{}">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'relatedNo'">
            <CopyText :text="record.related?.no ?? record.related?.order_no">
              <a @click="detail(record)">{{ record.related?.no ?? record.related?.order_no }}</a>
            </CopyText>
          </template>
          <template v-if="column.dataIndex === 'into_status'">
            <a-tag :color="TagColor[text]">{{ getDescByValue('STORE_STATUS_ENUM', Number(text)) }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'related_type'">
            {{ getDescByValue('INTO_STATUS_ENUM', text) }}
          </template>
          <template v-if="column.dataIndex === 'sign_amount'">
            <span>{{ Number(text).toFixed(2) ?? '0.00' }}</span>
          </template>
          <template v-if="column.dataIndex === 'order_amount'">
            <span>{{ Number(text).toFixed(2) ?? '0.00' }}</span>
          </template>
          <template v-if="column.dataIndex === 'warehouse_name'">
            <span
              >{{ record.related?.warehouse?.name }}<span v-if="record.related?.warehouse?.attribute_type">({{ getDescByValue('WAREHOUSE_ATTRIBUTE_TYPE', record.related?.warehouse?.attribute_type) }})</span>
            </span>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <div class="smart-table-operate" v-if="record.into_status !== 4">
              <a-button @click="detail(record)" type="link" style="color: #97999c" v-privilege="'goods:update'" v-if="record.into_status !== 1">详情</a-button>
              <a-button @click="print(record)" type="link" v-privilege="'goods:update'" v-if="record.into_status !== 1">打印</a-button>
              <!-- <a-button @click="modifyAction(record)" type="link" danger v-privilege="'goods:update'" v-if="[INTO_STATUS_ENUM.PurchaseOrder.value, INTO_STATUS_ENUM.CompanyTransferOrder.value].includes(record.related_type) && record.into_status === 1">驳回</a-button> -->
              <!-- <a-button @click="sign(record)" type="link" v-privilege="'goods:update'" v-if="record.into_status == 1">签收</a-button> -->
            </div>
          </template>
        </template>
        <template #summary>
          <a-table-summary fixed>
            <a-table-summary-row>
              <a-table-summary-cell>总计</a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.total_num || 0 }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.total_sign_amount || 0 }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell>
                <a-typography-text type="danger">{{ total_amount.total_order_amount || 0 }}</a-typography-text>
              </a-table-summary-cell>
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
              <a-table-summary-cell />
            </a-table-summary-row>
          </a-table-summary>
        </template>
      </a-table>
    </div>
    <div class="smart-query-table-page query-table-page">
      <a-pagination showSizeChanger showQuickJumper show-less-items :pageSizeOptions="PAGE_SIZE_OPTIONS" :defaultPageSize="queryForm.limit" v-model:current="queryForm.page" v-model:pageSize="queryForm.limit" :total="total" @change="queryData" @showSizeChange="queryData" :show-total="(total) => `共${total}条`" />
    </div>
    <!---------- 签收 begin ----------->
    <PurchaseSignDetailsModal ref="signRef" @reload-list="queryData" />
    <!---------- 签收 end ----------->
    <!---------- 详情 begin ----------->
    <PurchaseReceiptDetailsModal ref="detailRef" @reload-list="queryData" />
    <!---------- 详情 end ----------->
    <PurchaseReceiptPrintModal ref="printRef" />
  </a-card>
</template>
<script setup lang="ts">
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import PurchaseSignDetailsModal from './components/purchase-sign-details-modal.vue'
import PurchaseReceiptDetailsModal from './components/purchase-receipt-details-modal.vue'
import PurchaseReceiptPrintModal from './components/purchase-receipt-print-modal.vue'
import { returnOrderApi } from '@/api/business/storage/store-api'
import { PAGE_SIZE_OPTIONS, DEFAULT_TIME_RANGE } from '@/constants/system/common-const'
import Select from '@/components/business/select/index.vue'
import TableOperator from '@/components/support/table-operator/index.vue'
import SearchFormCollapse from '@/components/support/search-form-collapse/index.vue'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import EnumSelect from '@/components/framework/enum-select/index.vue'
import _ from 'lodash'
import { message, Modal } from 'ant-design-vue'
import { errorSentry } from '@/lib/error-sentry'
import { useQuery } from '@/hooks/web/use-query-hook'
import { QUERY_FORM_OP } from '@/constants/support/query-form-op-const'
import { useEnums } from '@/hooks/plugins/useEnums'
import { useAppConfigStore } from '@/store/modules/app-store'
import { useResize } from '@/hooks/web/use-resize-hook'
import { useLoadingStore } from '@/store/modules/loading-store'
import { WAREHOUSE_TYPE, WAREHOUSE_ATTRIBUTE_TYPE } from '@/constants/business/storage/warehouse/warehouse-const'

const appConfigStore = useAppConfigStore()
const loadingStore = useLoadingStore()
const { getDescByValue } = useEnums()
// ----------------------------- tag入库状态 -----------------------------
enum TagColor {
  'blue' = 1,
  'green',
  'orange',
  'red'
}
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY, expand } = useResize()

// ---------------------------- 表格列 ----------------------------

const columns = computed(() => [
  {
    title: '源订单号',
    dataIndex: 'relatedNo',
    width: appConfigStore.$state.compactFlag ? 150 : 180
  },
  {
    title: '司机/业务员',
    dataIndex: ['related', 'customer', 'name'],
    width: 180
  },
  {
    title: '入库仓库',
    dataIndex: 'warehouse_name'
  },
  {
    title: '入库类型',
    dataIndex: 'related_type'
  },
  {
    title: '入库状态',
    dataIndex: 'into_status',
    width: 60
  },
  {
    title: '签收数量',
    dataIndex: 'sign_num',
    width: 100
  },
  {
    title: '签收金额',
    dataIndex: 'sign_amount',
    width: 100
  },
  {
    title: '订单金额',
    dataIndex: 'order_amount',
    width: 100
  },
  {
    title: '源单备注',
    dataIndex: ['related', 'remark'],
    width: 80
  },
  {
    title: '签收备注',
    dataIndex: 'sign_remark'
  },
  {
    title: '单据日期',
    dataIndex: 'create_time'
  },
  {
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
    width: appConfigStore.$state.compactFlag ? 120 : 140
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------
const total_amount = ref({
  total_order_amount: 0,
  total_sign_amount: 0,
  total_num: 0
})
const warehouse = ref('')
const { queryForm, queryFormOp, tableData, tableLoading, total, resetQuery, onSearch, queryData } = useQuery({
  fetchDataApi: async (params) => {
    const data = {
      ...params,
      warehouse: warehouse.value
    }
    const res = await returnOrderApi.queryReturnOrderList(data)
    const { val, ...other } = res.data
    total_amount.value = _.pick(other, Object.keys(total_amount.value))
    return {
      list: res.data.data,
      total: res.data.total
    }
  },
  queryFormFilter: {
    no: '',
    create_time: DEFAULT_TIME_RANGE.value,
    into_status: null,
    related_type: null,
    dealer_id: null,
    salesman_id: null,
    driver_id: null
  },
  queryFormOp: {
    no: QUERY_FORM_OP['模糊查询'],
    create_time: QUERY_FORM_OP['范围查询'],
    into_status: QUERY_FORM_OP['全等查询'],
    related_type: QUERY_FORM_OP['全等查询'],
    dealer_id: QUERY_FORM_OP['全等查询'],
    salesman_id: QUERY_FORM_OP['全等查询'],
    driver_id: QUERY_FORM_OP['全等查询']
  }
})

onActivated(() => {
  queryData()
})

// Select查询参数
const selectFetchParams = {
  warehouse: {
    filter: {
      warehouse_type: WAREHOUSE_TYPE.FIXED.value,
      attribute_type: WAREHOUSE_ATTRIBUTE_TYPE.OTHER.value
    },
    op: {
      warehouse_type: QUERY_FORM_OP['全等查询'],
      attribute_type: QUERY_FORM_OP['不等查询']
    },
    fields: 'id,name'
  }
}

const resetQueryData = () => {
  warehouse.value = ''
  resetQuery()
}

// ---------------------------- 签收 ----------------------------
const signRef = ref()

const sign = (goodsData) => {
  signRef.value.showDrawer(goodsData)
}
// ---------------------------- 详情 ----------------------------
const detailRef = ref()

const detail = (goodsData) => {
  detailRef.value.showDrawer(goodsData)
}

// ---------------------------- 打印 ----------------------------
const printRef = ref()

const print = async (goodsData) => {
  const res = await returnOrderApi.detail({ id: goodsData.id })
  console.log(goodsData, res.data)

  printRef.value.showDrawer(goodsData, res.data)
}
// ---------------------------- 驳回 ----------------------------
function modifyAction(rowData) {
  Modal.confirm({
    title: '提示',
    content: '确定要驳回【' + rowData.no + '】吗?',
    okText: '驳回',
    okType: 'danger',
    onOk() {
      singleDeleteAction(rowData)
    },
    cancelText: '取消',
    onCancel() {}
  })
}

async function singleDeleteAction(rowData) {
  try {
    loadingStore.show()
    const res = await returnOrderApi.modifyIn({ id: rowData.id })
    message.success(res.msg)
    queryData()
  } catch (e) {
    message.error(e.msg)
    errorSentry.captureError(e)
  } finally {
    loadingStore.hide()
  }
}
// ------------------------------- 导出和导入 ---------------------------------
// 导出
function onExport() {
  const { page, limit, ...filter } = queryForm.value
  const data = {
    filter: JSON.stringify(filter),
    op: JSON.stringify(queryFormOp)
  }
  returnOrderApi.exportXlsx(data)
}
</script>
